<template>
  <div class="document-setting-box">
    <div class="setting-title">文档格式预览设置</div>
    <je-table
      ref="leftTable"
      border
      auto-resize
      show-overflow="ellipsis"
      height="360"
      keep-source
      :size="tableSize"
      show-header-overflow
      :store="documentSettingStore"
      :draggable="false"
      resizable
      header-align="center"
      :scroll-y="{ mode: 'wheel' }"
      :edit-config="{
        trigger: 'click',
        mode: 'cell',
        showUpdateStatus: true,
        showInsertStatus: false,
      }"
    >
      <!-- <je-column title="操作" width="40" align="center" :draggable="false">
        <template #header>
          <i
            style="font-size: 16px; cursor: pointer"
            class="fal fa-plus"
            @click="addSettingColumn"
          ></i>
        </template>
        <template #default="{ row }">
          <i
            style="font-size: 16px; cursor: pointer"
            class="fal fa-times"
            @click="deleteSettingColumn(row)"
          ></i>
        </template>
      </je-column> -->
      <je-column type="seq" width="60" title="NO" align="center"> </je-column>
      <je-column field="type" title="类型" name="type" :draggable="false" align="center">
        <template #edit="{ row }">
          <je-input v-model:value="row.type" />
        </template>
      </je-column>
      <je-column
        field="format"
        title="格式"
        name="format"
        :edit-render="inputRender"
        :draggable="false"
        min-width="310"
      >
        <template #edit="{ row }">
          <je-input v-model:value="row.format" />
        </template>
      </je-column>
      <je-column
        field="previewWay"
        title="预览方式"
        name="previewWay"
        :edit-render="inputRender"
        :draggable="false"
        align="center"
      >
        <template #edit="{ row }">
          <je-select
            v-model:value="row.previewWay"
            style="width: 100%"
            :options="formatPreviewOptions(row)"
            @mouseenter="handleEnterWay(row)"
          >
          </je-select>
        </template>
        <template #default="{ row }">
          <span>{{ formatPreviewWay(row) }}</span>
        </template>
      </je-column>
    </je-table>
  </div>
</template>

<script>
  import { defineComponent, reactive, toRefs, onMounted, onUnmounted, onBeforeMount } from 'vue';
  import { Grid, Data, Select, Input, Modal } from '@jecloud/ui';
  import VueEvent from '@/helper/model/event';
  import { useOpenDialog } from '@/hooks';
  import { saveConfigData, getDicItemByCodes } from '@/api';
  export default defineComponent({
    name: 'DocumentSetting',
    components: {
      JeTable: Grid,
      JeColumn: Grid.Column,
      JeInput: Input,
      JeSelect: Select,
    },
    props: {
      dataAll: {
        type: Array,
        default: () => [],
      },
    },
    setup(props) {
      const state = reactive({
        tableSize: 'small', //紧凑
        inputRender: {
          autofocus: '.ant-input',
        },
        documentSettingStore: Data.Store.useGridStore({
          data: [],
        }),
        previewOptions: [],
        officeOptions: [], //office格式预览方式
        otherOptions: [], //其他格式预览方式
        setEqualArr: [],
      });
      const methods = {
        initDocumentSetting(setColumns) {
          state.documentSettingStore.loadData([...setColumns]);
        },
        addSettingColumn() {
          const settingParam = {
            setType: '', //类型
            setFormat: '', //格式
            previewWay: '', //预览方式
          };
          state.documentSettingStore.insert(settingParam, -1);
        },
        deleteSettingColumn(row) {
          state.documentSettingStore.remove(row);
        },

        formatPreviewWay(row) {
          let wayStr = '';
          state.previewOptions.forEach((item) => {
            if (item.value == row.previewWay) {
              wayStr = item.label;
            }
          });
          return wayStr;
        },
        formatPreviewOptions(row) {
          //转化下拉选项
          switch (row.type) {
            case 'Office':
            case 'office':
              return state.officeOptions;
            default:
              return state.otherOptions;
          }
        },
        handleEnterWay(row) {
          methods.formatPreviewOptions(row);
        },
        isChange() {
          if (state.setEqualArr.length != state.documentSettingStore.data.length) {
            return true;
          }
          for (let i = 0, j = state.documentSettingStore.data.length; i < j; i++) {
            if (
              state.setEqualArr[i].type != state.documentSettingStore.data[i].type ||
              state.setEqualArr[i].format != state.documentSettingStore.data[i].format ||
              state.setEqualArr[i].previewWay != state.documentSettingStore.data[i].previewWay
            ) {
              return true;
            }
          }
          return false;
        },
        // 点击保存回调
        clickCallback() {
          if (methods.isChange()) {
            const saveSetArr = [];
            state.documentSettingStore.data.forEach((setItem) => {
              const item = {
                type: setItem.type,
                format: setItem.format,
                previewWay: setItem.previewWay,
              };
              saveSetArr.push(item);
            });
            const saveSetObj = {
              JE_SYS_DOCUMENT_FORMAT_PREVIEW_SETTING: saveSetArr,
            };
            saveConfigData({
              attribute: 'document-setting',
              allFields: JSON.stringify(saveSetObj),
              type: '',
            }).then(() => {
              state.setEqualArr = JSON.parse(
                JSON.stringify(saveSetObj.JE_SYS_DOCUMENT_FORMAT_PREVIEW_SETTING),
              );
              VueEvent.emit('changeAllData', { item: 'document-setting', formState: saveSetObj });
              Modal.notice('保存成功', 'success');
              state.documentSettingStore.loadData([
                ...saveSetObj.JE_SYS_DOCUMENT_FORMAT_PREVIEW_SETTING,
              ]);
            });
          } else {
            // 如果显示了子页面就不提示
            Modal.notice('无数据操作!', 'info');
          }
        },
        // 判断是否跳转
        changeBar() {
          VueEvent.emit('saveResult', !methods.isChange());
        },
        // 依据formstate数据，判断是否允许离开
        isSaveCallback() {
          if (!methods.isChange()) return methods.changeBar();
          useOpenDialog({
            attribute: 'team-config',
            allFields: JSON.stringify(state.setEqualArr),
          });
        },
        initOfficeWay() {
          getDicItemByCodes({ ddListCodes: 'JE_DOCUMENT_PREVIEW_WAY' }).then((res) => {
            state.officeOptions = [];
            const officeDicts = res.JE_DOCUMENT_PREVIEW_WAY;
            officeDicts.forEach((dictItem) => {
              const officeItem = {
                label: dictItem.text,
                value: dictItem.code,
              };
              state.officeOptions.push(officeItem);
            });
            methods.initOtherWay();
          });
        },
        initOtherWay() {
          getDicItemByCodes({ ddListCodes: 'JE_META_ENA_DIS' }).then((res) => {
            state.otherOptions = [];
            const otherDicts = res.JE_META_ENA_DIS;
            otherDicts.forEach((dictItem) => {
              const otherItem = {
                label: dictItem.text,
                value: dictItem.code,
              };
              state.otherOptions.push(otherItem);
            });
            state.previewOptions = [];
            state.previewOptions = state.officeOptions.concat(state.otherOptions);
          });
        },
      };
      onBeforeMount(() => {
        methods.initOfficeWay();
      });
      onMounted(() => {
        props.dataAll.forEach((data) => {
          if (data.key == 'DocumentSetting') {
            methods.initDocumentSetting(data.items);
            state.setEqualArr = JSON.parse(JSON.stringify(data.items));
          }
        });
        VueEvent.on('toolbarSaveEvent', methods.clickCallback);
        VueEvent.on('isSave', methods.isSaveCallback);
      });
      onUnmounted(() => {
        VueEvent.off('toolbarSaveEvent', methods.clickCallback);
        VueEvent.off('isSave', methods.isSaveCallback);
      });
      return {
        ...toRefs(state),
        ...methods,
      };
    },
  });
</script>
<style scoped lang="less">
  .document-setting-box {
    width: 100%;
    padding: 30px;
    .setting-title {
      margin-bottom: 15px;
      font-size: 16px;
      color: #3f3f3f;
    }
  }
</style>
